package com.bleet.securitysms;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import com.bleet.securitysms.db.DBAdapter;
import com.bleet.securitysms.db.DataMap;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;


public class Security {
	private final static String URI = "content://sms/";
	
	public void encrypt(Context ctx, String number, String ssmsId){
		Thread t = new Thread(new enRunnable(ctx, number, ssmsId));
		t.start();
	}
	
	public void decrypt(Context ctx, String number, String ssmsId){
		Thread t = new Thread(new deRunnable(ctx, number, ssmsId));
		t.start();
	}
	
	class enRunnable implements Runnable{
		private Context ctx = null;
		private String number = null;
		private String ssmsId = null;
		public enRunnable(Context ctx, String number, String ssmsId) {
			this.ctx = ctx;
			this.number = number;
			this.ssmsId = ssmsId;
		}

		@Override
		public void run() {
			SMSCursorHandler(ctx, number, true, ssmsId);
		}
	}
	
	class deRunnable implements Runnable{
		private Context ctx = null;
		private String number = null;
		private String ssmsId = null;
		public deRunnable(Context ctx, String number, String ssmsId) {
			this.ctx = ctx;
			this.number = number;
			this.ssmsId = ssmsId;
		}

		@Override
		public void run() {
			SMSCursorHandler(ctx, number, false, ssmsId);
		}
	}
	
	public static void SMSCursorHandler(Context ctx, String number, boolean flag, String ssmsId){
		ContentResolver cr = ctx.getContentResolver();
		String [] fields = new String [] {"_id", "body"};
		String where = "address like ? or person like ?";
		String [] params = new String [] {"%" + number, "%" +number};
		Cursor c = cr.query(Uri.parse(URI), fields, where, params, null);
		for(c.moveToFirst(); ! c.isAfterLast(); c.moveToNext()){
			String id = c.getString(c.getColumnIndex("_id"));
			String body = c.getString(c.getColumnIndex("body"));
			String where1 = "_id = ?";
			String [] params1 = new String [] {id};
			ContentValues cv = new ContentValues();
			String nBody = null;
			if(flag == true){
				if(body.endsWith("--ssms")){
					continue;
				}
				nBody = getSBody(body);
				cv.put("body", nBody);
				cr.update(Uri.parse(URI), cv, where1, params1);
			}else {
				if(!body.endsWith("--ssms")){
					continue;
				}
				nBody = getUNSBody(body);
				cv.put("body", nBody);
				cr.update(Uri.parse(URI), cv, where1, params1);
			}
		}
		
		DBAdapter db = new DBAdapter(ctx);
		db.open();
		DataMap data = new DataMap();
		if(flag == true){
			data.putString(DBAdapter.MODE, "1");
			data.putString(DBAdapter.MESSAGE_COUNT, String.valueOf(c.getCount()));
		}else {
			data.putString(DBAdapter.MODE, "0");
			data.putString(DBAdapter.MESSAGE_COUNT, String.valueOf(c.getCount()));
		}
		db.update(Long.parseLong(ssmsId), data);
		db.close();
		((SecuritySMS)ctx).getRefreshHandler().viewFresh(0);
	}
	
	private static String getSBody(String body) {
		if (body == null) return null; 
		return Base64.encode(body.getBytes()) + "--ssms";
	}

	private static String getUNSBody(String body) {
		if (body == null) return null;
		body = body.replaceAll("--ssms", "");
		try {
			return new String(Base64.decode(body));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String toMd5(byte[] bytes) {
		try {
			MessageDigest algorithm = MessageDigest.getInstance("MD5");
			algorithm.reset();
			algorithm.update(bytes);
			return toHexString(algorithm.digest(), "");
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
	}

	public static String toHexString(byte[] bytes, String separator) {
		StringBuilder hexString = new StringBuilder();
		for (byte b : bytes) {
			hexString.append(Integer.toHexString(0xFF & b)).append(separator);
		}
		return hexString.toString();
	}
}
